package com.zhz.thymeleafmp.web;

import com.zhz.thymeleafmp.entity.Dept;
import com.zhz.thymeleafmp.entity.User;
import com.zhz.thymeleafmp.service.DeptService;
import com.zhz.thymeleafmp.service.UserService;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.List;

@Controller
@RequestMapping("/user")
public class UserController {

    @Resource
    private UserService userService;

    @Resource
    private DeptService deptService;

    @GetMapping("/main")
    public String main() {
        return "index";
    }

    @GetMapping("/users")
    public String userList(Model model) {
        List<User> list = userService.getUserList();
        model.addAttribute("users",list);
        return "list";
    }

    @GetMapping("/add")
    public String toAdd(Model model){
        model.addAttribute("depts", deptService.getDepts());
        return "add";
    }

    @PostMapping("/save")
    public String addUser(User user) {
        boolean result = userService.addUser(user);
        if (result) {
            return "redirect:/user/users";
        }
        return "add";
    }

    @GetMapping("/modify/{id}")
    public String toModify(@PathVariable("id") Long id,Model model) {
        User user = userService.getUser(id);
        List<Dept> deptList = deptService.getDepts();

        model.addAttribute("user",user);
        model.addAttribute("depts",deptList);

        return "add";
    }

    @PutMapping("/save")
    public String modifySave(User user) {
        boolean result = userService.modify(user);
        if (result) {
            return "redirect:/user/users";
        }
        return "forward:/user/modify/"+user.getId();
    }

    @DeleteMapping("/del/{id}")
    public String delete(@PathVariable("id") Long id) {
        boolean result = userService.delete(id);
        if (result) {
            return "redirect:/user/users";
        }
        return "redirect:/user/users";
    }

}
